package org.luckyjourney.util;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * @author 飒飒
 * @ClassName HttpClientUtils
 * @description: TODO
 * @date 2024年03月12日
 * @version: 1.0
 */

public class HttpClientUtils {
    private static final Logger log = LoggerFactory.getLogger(HttpClientUtils.class);


    /**
     * 电控调用
     * @param url
     * @param map
     * @param charset
     * @param token
     * @return
     */
    public static String doPost(String url, Map<String, Object> map, String charset, String token) {
//        log.info("开始调用工具类------->");
//        log.info("开始调用工具类参数---->:url={},map={},token={}", url, map, token);
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            httpClient = HttpClients.createDefault();
            httpPost = new HttpPost(url);
            //设置请求头参数
            httpPost.setHeader("Content-type", "application/json; charset=utf-8");
            //token  根据接口参数来
            httpPost.setHeader("X-Token", token);
            //设置参数
            StringEntity entity = new StringEntity(JSON.toJSONString(map), Charset.forName("UTF-8"));
            entity.setContentType("application/json");
            httpPost.setEntity(entity);

            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, charset);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
//            log.error("调用接口失败---->"+ ex.getMessage());
        }finally {
//            log.info("开始调用工具类失败finally--->");
        }
//        log.info("结束调用工具类---->");
        return result;
    }


    public static String sendPostRequestWithToken(String url, String token, String payload) {
        try {
            URL requestUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod("POST");

            // 添加Token到请求头
//            connection.setRequestProperty("Authorization", "Bearer " + token);
            connection.setRequestProperty("token", token);

            // 允许输入输出流
            connection.setDoOutput(true);
            connection.setDoInput(true);

            // 设置请求体
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(payload.getBytes("UTF-8"));
            outputStream.close();

            // 获取响应
            int responseCode = connection.getResponseCode();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            // 返回响应结果
            return response.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String sendGetRequestWithToken(String url, String token, String payload) {
        try {
            URL requestUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod("Get");

            // 添加Token到请求头
//            connection.setRequestProperty("Authorization", "Bearer " + token);
            connection.setRequestProperty("token", token);

            // 允许输入输出流
            connection.setDoOutput(true);
            connection.setDoInput(true);

            // 设置请求体
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(payload.getBytes("UTF-8"));
            outputStream.close();

            // 获取响应
            int responseCode = connection.getResponseCode();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            // 返回响应结果
            return response.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
